package org.kjtc.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kjtc.constants.WXConstants;
import org.kjtc.emoji.EmojiParser;
import org.kjtc.entity.WechatUser;
import org.kjtc.service.WeChartService;
import org.kjtc.service.WxUserService;
import org.kjtc.weChatUtil.CommonUtil;
import org.kjtc.weChatUtil.WXUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class UserController {

    private static Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private WeChartService weChartService;
    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private WXUtils wxUtils;
    
    @RequestMapping(value = "/searchWechatUser")
    @ResponseBody
    public Map<String, Object> searchWechatUser(WechatUser wechatUser,
            @RequestParam(value="pageNum", defaultValue="1") Integer pageNum, @RequestParam(value="pageSize", defaultValue="10") Integer pageSize) {

        Page page = PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        List<WechatUser> userlist = null;
        try {
            userlist = weChartService.searchWechatUser(null);
            map.put("userlist", userlist);
            map.put("total", page.getTotal());
            if (redisTemplate.hasKey("pullSubscribe")) {
                if ("pulled".equals((String)redisTemplate.opsForValue().get("pullSubscribe"))) {
                    redisTemplate.opsForValue().set("pullSubscribe", "");
                    map.put("result", "Pulled");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("userlist", "Error");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/getWechatUserName")
    @ResponseBody
    public Object getWechatUserName(WechatUser wechatUser) {
        return weChartService.getWechatUserName(wechatUser);
    }

    @RequestMapping(value = "/saveWechatUser")
    @ResponseBody
    public Map<String, Object> saveWechatUser(WechatUser wechatUser) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            wechatUser.setCreateUser("weChat");
            wechatUser.setUpdateUser("weChat");
            weChartService.saveWechatUser(wechatUser);
            map.put("result", "Success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "Error");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/updateWechatUser")
    @ResponseBody
    public Map<String, Object> updateWechatUser(WechatUser wechatUser) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            wechatUser.setUpdateUser("weChat");
            weChartService.updateWechatUser(wechatUser);
            map.put("result", "Success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "Error");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/deleteWechatUser")
    @ResponseBody
    public Object deleteWechatUser(String weChatIDList) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            int count = weChartService.deleteWechatUser(weChatIDList);
            if (count > 0) {
                map.put("result", "Success");
            } else {
                map.put("result", "NotFound");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", "Error");
            return map;
        }
        return map;
    }

    @RequestMapping(value = "/syncWechatUser")
    @ResponseBody
    public Object syncWechatUser(String weChatIDList) {

        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isEmpty(weChatIDList)) {
            map.put("result", "NotFound");
        } else {
            try {
                String token = CommonUtil.getToken(CommonUtil.appid, CommonUtil.appsecret, redisTemplate);
                if (StringUtils.isEmpty(token)) {
                    map.put("result", "Error");
                    logger.error("同步用户信息失败：获取微信(token)失败");
                    return map;
                }
                String requestMethod = null;
                JSONObject userJson = null;
                JSONArray userListArray = null;
                if (weChatIDList.indexOf(",") > 0) {
                    String[] weChatIDArray = weChatIDList.split(",");
                    JSONObject userListJson = new JSONObject();
                    userListArray = new JSONArray();
                    for (String weChatID : weChatIDArray) {
                        userJson = new JSONObject();
                        userJson.put("openid", weChatID);
                        userJson.put("lang", "zh_CN");
                        userListArray.add(userJson);
                    }
                    userListJson.put("user_list", userListArray);
                    weChatIDList = userListJson.toString();
                    requestMethod = "POST";
                    userListArray = null;
                    userJson = null;
                }
                userJson = CommonUtil.getWechatUserInfo(token, weChatIDList, requestMethod);
                if (userJson != null) {
                    if (userJson.has("user_info_list")) {
                        userListArray = JSONArray.fromObject(userJson.getString("user_info_list"));
                    } else {
                        userListArray = new JSONArray();
                        userListArray.add(userJson);
                    }
                    WechatUser wechatUser = null;
                    int count = userListArray.size();
                    String notFoundList = null;
                    for (int i = 0; i < count; i++) {
                        userJson = userListArray.getJSONObject(i);
                        if (userJson.has("openid") && !StringUtils.isEmpty(userJson.getString("openid"))) {
                            wechatUser = new WechatUser();
                            wechatUser.setWeChatID(userJson.getString("openid"));
                            if (userJson.has("subscribe") && "1".equals(userJson.getString("subscribe"))) {
                                Date date = new Date();
                                String nickname = "";
                                if (userJson.has("nickname")) {
                                    nickname = userJson.getString("nickname");
                                    nickname = EmojiParser.replaceAllEmojis(nickname, "*");
                                    if (userJson.has("remark") && !StringUtils.isEmpty(userJson.getString("remark"))) {
                                        nickname += "(" + userJson.getString("remark") + ")";
                                    }
                                    wechatUser.setWeChatNickName(nickname);
                                }
                                if (userJson.has("headimgurl")) {
                                    wechatUser.setWeChatImageUrl(userJson.getString("headimgurl"));
                                }
                                if (userJson.has("subscribe_time")) {
                                    date.setTime(Long.parseLong(userJson.getString("subscribe_time")) * 1000);
                                }
                                wechatUser.setUpdateUser("weChat");
                                wechatUser.setSubscribeTime(date);
                                wechatUser.setEnabled(true);
                            } else {
                                wechatUser.setEnabled(false);
                                if (notFoundList == null) {
                                    notFoundList = userJson.getString("openid");
                                } else {
                                    notFoundList += "<br/>" + userJson.getString("openid");
                                }
                                map.put("notFoundList", notFoundList);
                            }
                            weChartService.syncWechatUser(wechatUser);
                        }
                        wechatUser = null;
                    }
                    if (notFoundList == null) {
                        map.put("result", "Success");
                    } else {
                        map.put("result", "NotFound");
                    }
                } else {
                    map.put("result", "NotFound");
                }
                requestMethod = null;
                userJson = null;
                userListArray = null;
            } catch (Exception e) {
                e.printStackTrace();
                map.put("result", "Error");
                return map;
            }
        }
        return map;
    }

    @RequestMapping(value = "/pullSubscribeUser")
    @ResponseBody
    public Object pullSubscribeUser(final String nextOpenid) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("result", "Success");
        if (redisTemplate.hasKey("pullSubscribe")) {
            if ("pulling".equals((String)redisTemplate.opsForValue().get("pullSubscribe"))) {
                map.put("result", "Pulling");
                return map;
            } else if ("pulled".equals((String)redisTemplate.opsForValue().get("pullSubscribe"))) {
                redisTemplate.opsForValue().set("pullSubscribe", "");
                map.put("result", "Pulled");
            }
        }
        final String token = CommonUtil.getToken(CommonUtil.appid, CommonUtil.appsecret, redisTemplate);
        if (StringUtils.isEmpty(token)) {
            map.put("result", "Error");
            logger.error("拉取关注用户信息失败：获取微信(token)失败");
            return map;
        }
        redisTemplate.opsForValue().set("pullSubscribe", "pulling");
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                JSONArray openid = null;
                openid = CommonUtil.pullSubscribeUser(token, nextOpenid, openid);
                if (openid != null) {
                    JSONObject userJson = null;
                    JSONArray userListArray = new JSONArray();
                    int count = openid.size();
                    for (int i = 0; i < count; i++) {
                        userJson = new JSONObject();
                        userJson.put("openid", openid.getString(i));
                        userJson.put("lang", "zh_CN");
                        userListArray.add(userJson);
                    }
                    JSONObject userListJson = new JSONObject();;
                    userListJson.put("user_list", userListArray);
                    userListArray = null;
                    userJson = null;
                    userJson = CommonUtil.getWechatUserInfo(token, userListJson.toString(), "POST");
                    userListJson = null;
                    if (userJson != null) {
                        if (userJson.has("user_info_list")) {
                            userListArray = JSONArray.fromObject(userJson.getString("user_info_list"));
                        }
                    }
                    if (userListArray != null) {
                        count = userListArray.size();
                        for (int i = 0; i < count; i++) {
                            userJson = userListArray.getJSONObject(i);
                            if (userJson.has("openid") && !StringUtils.isEmpty(userJson.getString("openid"))) {
                                WechatUser wechatUser = new WechatUser();
                                wechatUser.setWeChatID(userJson.getString("openid"));
                                int userCount = weChartService.checkWechatUserOnly(wechatUser);
                                if (userJson.has("subscribe") && "1".equals(userJson.getString("subscribe"))) {
                                    Date date = new Date();
                                    String nickname = "";
                                    if (userJson.has("nickname")) {
                                        nickname = userJson.getString("nickname");
                                        nickname = EmojiParser.removeAllEmojis(nickname);
                                        if (userJson.has("remark") && !StringUtils.isEmpty(userJson.getString("remark"))) {
                                            nickname += "(" + userJson.getString("remark") + ")";
                                        }
                                        wechatUser.setWeChatNickName(nickname);
                                    }
                                    if (userJson.has("headimgurl")) {
                                        wechatUser.setWeChatImageUrl(userJson.getString("headimgurl"));
                                    }
                                    if (userJson.has("subscribe_time")) {
                                        date.setTime(Long.parseLong(userJson.getString("subscribe_time")) * 1000);
                                    }
                                    wechatUser.setUpdateUser("weChat");
                                    wechatUser.setSubscribeTime(date);
                                    wechatUser.setEnabled(true);
                                } else {
                                    wechatUser.setEnabled(false);
                                }
                                if (userCount > 0) {
                                    weChartService.syncWechatUser(wechatUser);
                                } else {
                                    wechatUser.setCreateUser("weChat");
                                    weChartService.saveWechatUser(wechatUser);
                                }
                                wechatUser = null;
                            }
                        }
                    }
                }
                redisTemplate.opsForValue().set("pullSubscribe", "pulled");
            }
        });
        t.start();
        return map;
    }

    /**
     * 保存（获取）code
     *
     *
     * 微信网页授权
     *      var fromurl ="http://xiaokejia.4kb.cn/authorize";
     *      var url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0e82324b8c475e52&redirect_uri='+encodeURIComponent(fromurl)+'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
     * 第一步：用户同意授权，获取code
     * 第二步：通过code换取网页授权access_token

    *
    *
    * */
    @RequestMapping(value = "/keepCode")
    @ResponseBody
    public Object keepCode(HttpServletRequest request) throws Exception {
        // 跳转页面标识
        String state = request.getParameter("state");
        // 通过code获取access_token
        String code = request.getParameter("code");
        logger.info("authorize:code:{}"+ code);

        // 获取access_token和openid
        com.alibaba.fastjson.JSONObject jsonToken = wxUtils.getJsapiAccessTokenByCode(code);

        if (null == jsonToken) {
            return WXConstants.ERROR;
        }

        // 判断用户是否在系统中是一个用户
        String unionid = jsonToken.getString("unionid");
        if (StringUtils.isBlank(unionid)) {
            return WXConstants.ERROR;
        }


        return WXConstants.SUCCESS;
    }

    /**
     * 保存（获取）用户信息
     *
     *
     * 微信网页授权
     *      var fromurl ="http://xiaokejia.4kb.cn/authorize";
     *      var url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0e82324b8c475e52&redirect_uri='+encodeURIComponent(fromurl)+'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
     * 第一步：用户同意授权，获取code
     * 第二步：通过code换取网页授权access_token
     * 第三步：通过access_token和openid请求获取用户信息(需scope为 snsapi_userinfo)
     * @return str
     *
     * @author xiaojinlu
     * @date
     *@ApiOperation(value = "微信支付|网页授权", httpMethod = "GET", notes = "获取前端微信用户的网页授权，得到用户基础信息")
     *
     *
     * */
    @RequestMapping("/userinfo")
    public String userinfo(HttpServletRequest request, ModelMap map) {
        //保存用户信息
        wxUserService.setUserInfo(request,map);

        return "mapPile/position";


    }
}
